import { Button, Modal } from 'antd';
import { Table, Form, Input, Select, Space } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { getUserList, deleteUser } from '@/api';
import { PageParams, User } from '@/types';
import { useState, useEffect, useRef } from 'react';
import { formatDate } from '@/utils';
import CreateUser from './createUser';
import { IAction } from '@/types/modal';
import { message } from '@/utils/AntdGlobal';
import AuthButton from '@/components/AuthButton';

export default function UserList() {
  const columns: ColumnsType<User.UserItem> = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId'
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName'
    },
    {
      title: '用户邮箱',
      dataIndex: 'userEmail',
      key: 'userEmail'
    },
    {
      title: '用户角色',
      key: 'role',
      dataIndex: 'role',
      render(role: number) {
        return {
          0: '超级管理员',
          1: '管理员',
          2: '体验管理员',
          3: '普通用户'
        }[role];
      }
    },
    {
      title: '用户状态',
      key: 'state',
      dataIndex: 'state',
      render(state: number) {
        return {
          1: '在职',
          2: '离职',
          3: '试用期'
        }[state];
      }
    },
    {
      title: '注册时间',
      key: 'createTime',
      dataIndex: 'createTime',
      render: (createTime: Date) => {
        return formatDate(createTime, 'yyyy-MM-dd');
      }
    },
    {
      title: '操作',
      key: 'opration',
      render: record => {
        return (
          <Space>
            <Button type='text' onClick={() => handleEditor(record)}>
              编辑
            </Button>
            <Button type='text' danger onClick={handleDelete([record.userId])}>
              删除
            </Button>
          </Space>
        );
      }
    }
  ];
  const [form] = Form.useForm();
  const userRef = useRef<{
    open: (type: IAction, data?: User.UserItem) => void;
  }>();
  const [userList, setUserList] = useState<User.UserItem[]>();
  const [total, setTotal] = useState<number>(0);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10
  });
  let userIds: number[] = [];
  // 获取用户列表
  const getUserData = async (params: PageParams) => {
    const values = form.getFieldsValue();
    const data = await getUserList({
      ...values,
      pageNum: params.pageNum,
      pageSize: params.pageSize || pagination.pageSize
    });
    setUserList(data.list);
    setTotal(data.page.total);
  };
  const handleSearch = () => {
    getUserData({
      pageNum: 1
    });
  };
  const handleTableChange = (current: number, pageSize: number) => {
    setPagination({
      current,
      pageSize
    });
  };
  const handleRest = () => {
    form.resetFields();
  };
  const handleCreate = () => {
    userRef.current?.open('create');
  };
  const handleEditor = (record: User.UserItem) => {
    userRef.current?.open('edit', record);
  };
  const handleDelete = (userIds: number[]) => () => {
    Modal.confirm({
      title: '删除确认',
      content: <span>确定删除该用户吗?</span>,
      onOk: async () => {
        try {
          await deleteUser({ userIds });
          message.success('删除成功');
          getUserData({
            pageNum: 1
          });
        } catch (err) {
          message.error('删除失败');
          console.log(err);
        }
      }
    });
  };

  const handlePatchComfirm = () => {
    if (!userIds.length) {
      message.error('请选择你要删除的用户');
      return;
    }
    Modal.confirm({
      title: '删除确认该批用户',
      content: <span>确定删除该用户吗?</span>,
      onOk: async () => {
        try {
          await deleteUser({ userIds });
          message.success('删除成功');
          getUserData({
            pageNum: 1
          });
        } catch (err) {
          console.log(err);
        }
      }
    });
  };

  useEffect(() => {
    getUserData({
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    });
  }, [pagination.current, pagination.pageSize]);
  return (
    <div className='user-list'>
      <Form
        className='search-form'
        layout='inline'
        initialValues={{
          state: 1
        }}
        form={form}
      >
        <Form.Item name='userId' label='用户ID'>
          <Input placeholder='请输入用户ID'></Input>
        </Form.Item>
        <Form.Item name='userName' label='用户名称'>
          <Input placeholder='请输入用户名称'></Input>
        </Form.Item>
        <Form.Item name='state' label='用户状态'>
          <Select style={{ width: 120 }}>
            <Select.Option value={0}>所有</Select.Option>
            <Select.Option value={1}>在职</Select.Option>
            <Select.Option value={2}>离职</Select.Option>
            <Select.Option value={3}>试用期</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type='primary' className='mr10' onClick={handleSearch}>
            搜索
          </Button>
          <Button type='primary' danger onClick={handleRest}>
            重置
          </Button>
        </Form.Item>
      </Form>
      <div className='base-table'>
        <div className='header-wrapper'>
          <div className='title'>用户列表</div>
          <div className='active'>
            <AuthButton auth='create' onClick={handleCreate} type='primary'>
              新增
            </AuthButton>
            <Button type='primary' danger onClick={handlePatchComfirm}>
              批量删除
            </Button>
          </div>
        </div>
        <Table
          columns={columns}
          dataSource={userList}
          bordered
          rowSelection={{
            type: 'checkbox',
            onSelect: (record, selected) => {
              if (selected) userIds = [...userIds, record.userId];
              else userIds = userIds.filter(item => item !== record.userId);
            },
            onSelectAll: (selected, selectedRows) => {
              if (selected) userIds = selectedRows.map(item => item.userId);
              else userIds = [];
            }
          }}
          rowKey='userId'
          pagination={{
            position: ['bottomRight'],
            current: pagination.current,
            pageSize: pagination.pageSize,
            total,
            showTotal: total => {
              return `总共: ${total}条`;
            },
            onChange: handleTableChange
          }}
        />
      </div>
      <CreateUser
        mRef={userRef}
        update={() => {
          getUserData({
            pageNum: 1
          });
        }}
      ></CreateUser>
    </div>
  );
}
